package com.zhen.util.key;

import java.util.HashMap;
import java.util.Map;

/**
 * 系统生产Key工具类
 */
public class IoergGeneratorKey {

	private static Map<String,SnowflakeIdWorker> workerMap = new HashMap<>();
	/**
	 * 工作机器ID(0~31)
	 */
	private static long workerId;
	/**
	 * 数据中心ID(0~31)
	 */
	private static long dataCenterId;

	static {
		workerId = 0L;
		dataCenterId = 0L;

	}

	public static synchronized long nextId() {
		return nextId(workerId,dataCenterId);
	}

	public static synchronized long nextId(long workerId, long datacenterId) {
		String key = workerId + "_" + datacenterId;
		SnowflakeIdWorker snowflakeIdWorker = null;
		if(workerMap.containsKey(key)) {
			snowflakeIdWorker = workerMap.get(key);
		} else {
			snowflakeIdWorker = new SnowflakeIdWorker(workerId,datacenterId);
			workerMap.put(key,snowflakeIdWorker);
		}

		return snowflakeIdWorker.nextId();
	}
	//==============================Test=============================================

	/**
	 * 测试
	 */
	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		for (int i = 0; i < 10; i++) {
			Long id = IoergGeneratorKey.nextId(1,2);
			System.out.println(id.toString());
			//System.out.println(id);
		}
		System.out.println("耗时：" + (System.currentTimeMillis() - start));
	}

}
